package api_error

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/service/api_error/api_admin_error"
	"gitee.com/theegg/go-brick/app/service/api_error/api_partner_error"
	"gitee.com/theegg/go-brick/app/service/api_error/api_user_error"
	"strconv"
)

type ApiError struct {
	Platform     string
	Code         int
	Msg          string
	Params       []interface{}
	Data         interface{}
	Lang         string
	ErrorsConfig map[string]string
}

// 实例化一个错误
func New(platform string, lang string) *ApiError {
	err := new(ApiError)
	err.Platform = platform
	err.Lang = lang
	err.ErrorsConfig = GetErrorConfig(platform, lang)

	return err
}

// code赋值
func (ae *ApiError) WithCode(code int) *ApiError {
	ae.Code = code
	return ae
}

// 获取错误信息
func (ae *ApiError) GetMeg() string {
	codeStr := ae.CodeToString()
	if _, ok := ae.ErrorsConfig[codeStr]; !ok {

	}

	// 格式化字符串
	errStr := ae.ErrorsConfig[codeStr]
	errStr = fmt.Sprintf(errStr, ae.Params...)
	return errStr
}

// 错误参数添加
func (ae *ApiError) WithParams(params []interface{}) *ApiError {
	ae.Params = params
	return ae
}

// 返回数据添加
func (ae *ApiError) WithData(data interface{}) *ApiError {
	ae.Data = data
	return ae
}

// get error config
func GetErrorConfig(platform string, lang string) map[string]string {

	var errorConfig map[string]map[string]string
	switch platform {
	case "admin":
		errorConfig = api_admin_error.ErrorCodes
	case "partner":
		errorConfig = api_partner_error.ErrorCodes
	case "user":
		errorConfig = api_user_error.ErrorCodes
	case "default":
		errorConfig = api_user_error.ErrorCodes
	}

	// 如果不存在的语言 直接抛出错误
	if _, ok := errorConfig[lang]; !ok {
		fmt.Println(errorConfig)
		panic("sorry not exists error")
	}

	return errorConfig[lang]
}

// 获取code的字符串形态
func (ae *ApiError) CodeToString() string {
	return strconv.Itoa(ae.Code)
}
